package com.trustbook.visitor.value;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * 
 * <p>
 * Title: FSM Project
 * </p>
 * <p>
 * Description: This is a utility class which will print the field values of the
 * subclasses.<br>
 * Note : Do not use it in the doubly or circular linked list implementations,
 * doing so causes recursive infinite loop.
 * </p>
 * 
 * @author Rahul Mittal
 * @version 1.0
 */
public class BaseBeanHelper {
	public String toString() {
		StringBuffer result = new StringBuffer();
		result.append("[");
		// determine fields declared in this class only (no fields of
		// superclass)
		Field[] fields = this.getClass().getDeclaredFields();
		SortedSet sortedFields = new TreeSet();

		// retrieve field names and their values
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			if (Modifier.toString(field.getModifiers()).indexOf("final") == -1) {
				Object fieldValue = null;
				StringBuffer fieldName = null;
				try {
					fieldName = new StringBuffer(field.getName());
					Method method = this.getClass().getMethod("get" + fieldName.replace(0, 1, fieldName.substring(0, 1).toUpperCase()), null);
					fieldValue = method.invoke(this, null);
				} catch (Exception ex) {
					fieldValue = "*** COULD NOT GET VALUE ***";
				}
				sortedFields.add(fieldName.toString().toLowerCase() + "=" + fieldValue);
			}
		}
		// print the fields and values in sorted order, separated with a comma
		for (Iterator iter = sortedFields.iterator(); iter.hasNext();) {
			String data = (String) iter.next();
			result.append(data + (iter.hasNext() ? ", " : ""));
		}

		return result.toString() + " <super.toSring:" + super.toString() + ">]";
	}
}
